//
//  QDStringHelper.m
//  QDMetroClient
//
//  Created by YueWen on 2019/2/27.
//  Copyright © 2019 YueWen. All rights reserved.
//

#import "QDStringHelper.h"

@implementation QDStringHelper




+ (NSInteger)phoneLimit
{
    return 11 + 2;//空格需要两个字符
}

+ (NSString *)phoneString:(NSString *)text
{
    return [text stringByReplacingOccurrencesOfString:@" " withString:@""];
}



+ (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(nonnull NSString *)string complete:(nonnull void (^)(void))complete
{
    NSString *text = textField.text;
    
    if (textField.text.length == self.phoneLimit && range.length == 0) return false;//进行长度限制
    
    //转成可变字符串
    NSMutableString *mutaleText = [[NSMutableString alloc]initWithString:text];
    
    if (range.length == 0) {//追加
        
        if (range.location > mutaleText.length) {
            
            [mutaleText appendString:string];
        }else {
            
            [mutaleText insertString:string atIndex:range.location];
        }
        
    }else {//表删除
        
        if (range.location > mutaleText.length) {
            
            [mutaleText deleteCharactersInRange:NSMakeRange(mutaleText.length - 1, 1)];
        }else {
            
            //如果前一个是空格，扩展
            if ([mutaleText characterAtIndex:range.location] == ' ') {
                
                range.location = range.location - 1;
                range.length = range.length + 1;
            }
            
            [mutaleText replaceCharactersInRange:range withString:@""];
        }
    }
    
    textField.text = [self transToPhoneString:mutaleText];
    
    //主动触发变化条件
    complete();
    
    return false;
}




+ (NSString *)transToPhoneString:(NSMutableString *)phoneString
{
    //移除所有的空格
    [phoneString replaceOccurrencesOfString:@" " withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, phoneString.length)];
    
    //如果是4位或者8位
    if(phoneString.length >= 8){
        
        [phoneString insertString:@" " atIndex:7];
        [phoneString insertString:@" " atIndex:3];
        
    } else if (phoneString.length >= 4) {
        
        [phoneString insertString:@" " atIndex:3];
    }
    
    return phoneString;
}


@end
